package cn.lijiajia3515.cairo.core.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

public class ThrowableUtil {

	public static List<Throwable> extractCause(Throwable exception, Integer depth) {
		List<Throwable> cause = new ArrayList<>();
		while ((depth == null && cause.size() < 100) || (depth != null && cause.size() > depth)) {
			Throwable ex = exception.getCause() != null && !exception.equals(exception.getCause()) ? exception.getCause() : null;
			if (ex == null) {
				break;
			}

			cause.add(ex);
			exception = ex;
		}
		return cause;
	}

	public static String extractTrace(Throwable error) {
		StringWriter stackTrace = new StringWriter();
		error.printStackTrace(new PrintWriter(stackTrace));
		stackTrace.flush();
		return stackTrace.toString();
	}

}
